package com.suneee.role.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.suneee.context.page.Page;
import com.suneee.context.page.Sort;
import com.suneee.context.page.Sort.Order;
import com.suneee.orm.GenericDao;
import com.suneee.orm.util.WhereClauseBuilder;
import com.suneee.permission.dao.PermissionDao;
import com.suneee.role.bean.RoleDto;
import com.suneee.role.dao.RoleDao;
import com.suneee.role.entity.Role;
import com.suneee.role.service.impl.RoleServiceImpl;

@Repository("roleDao")
public class RoleDaoImpl extends GenericDao<Role, Integer>implements RoleDao {

	@Autowired
	private PermissionDao permissionDao;
	
	@Override
	public int[] authorizedPermission(Integer roleId, List<Integer> permissionIdList) {
		// TODO Auto-generated method stub
		String sql = "insert into t_role_permission values(?,?)";
		List<Object[]> objList = new ArrayList<>();
		for(Integer id : permissionIdList){
			Object[] objs = new Object[2];
			objs[0] = roleId;
			objs[1] = id;
			objList.add(objs);
		}
		int[] result = this.executeBatchUpdate(sql, objList);
		return result;
	}

	@Override
	public int deleteRoleBySQL(Integer roleId, String enterpriseCode) {
		// TODO Auto-generated method stub
		String sql = "delete from t_role where role_id = ? and enterprise_code = ?";
		Object[] objs = new Object[2];
		objs[0] = roleId;
		objs[1] = enterpriseCode;
		
		//删除角色之前,先将该角色授权的菜单关联关系删除 
		this.executeUpdate("delete from t_role_permission where role_id = ?", roleId);
		
		//删除角色
		return this.executeUpdate(sql, objs);
	}

	@Override
	public int[] deleteRelationBySQL(Integer roleId, List<Integer> permissionIdList) {
		// TODO Auto-generated method stub
		String sql = "delete from t_role_permission where role_id = ? and permission_id = ?";
		List<Object[]> objList = new ArrayList<>();
		for(Integer id : permissionIdList){
			Object[] temp = new Object[2];
			temp[0] = roleId;
			temp[1] = id;
			objList.add(temp);
		}
		return this.executeBatchUpdate(sql, objList);
	}

	@Override
	public Page<Role> roleList(RoleDto dto) {
		WhereClauseBuilder sbf = this.wrapWhereSQL(dto);
		return this.executeQuery(sbf.getSql(), dto, sbf.getArgs());
	}
	
	private WhereClauseBuilder wrapWhereSQL(RoleDto dto){
		WhereClauseBuilder sbf = new WhereClauseBuilder(" select * from t_role where 1=1 ");
		sbf.equals("role_id", dto.getRoleId());
		sbf.contains("name",dto.getName());
		sbf.equals("enterprise_code", dto.getEnterpriseCode());
		sbf.equals("code", dto.getCode());
		if(dto.getEnabled() != null){
			sbf.equals("enabled", dto.getEnabled() ? 1 : 0);
		}
		sbf.between("create_time", dto.getCreateTimeStart(), dto.getCreateTimeEnd());
		sbf.between("last_update_time", dto.getLastUpdateTimeStart(), dto.getLastUpdateTimeEnd());
		dto.setSort(new Sort("role_id",Order.DESC));
		sbf.appendWhere("  if( enterprise_code='suneee' ,name not in ('public_roles','管理员'),1=1)  ");
		return sbf;
	}

	@Override
	public Role roleDetail(Integer roleId, String enterpriseCode) {
		// TODO Auto-generated method stub
		Role role = this.select(roleId);
		if(role != null){
			String sql = "select * from t_permission where permission_id "
					+ "in (select permission_id from t_role_permission where role_id = "
					+ roleId + ") ";
			Object[] args = null;
			role.setPermissionList(permissionDao.executeQuery(sql, args));
		}
		return role;
	}

	@Override
	public int[] addAdminRole(Integer adminId, List<Integer> roleIdList) {
		// TODO Auto-generated method stub
		String sql = "insert into t_administrator_role values(?,?)";
		List<Object[]> objList = new ArrayList<>();
		for(Integer id : roleIdList){
			Object[] objs = new Object[2];
			objs[0] = adminId;
			objs[1] = id;
			objList.add(objs);
		}
		int[] result = this.executeBatchUpdate(sql, objList);
		return result;
	}

	@Override
	public int[] cancelAdminRole(Integer adminId, List<Integer> roleIdList) {
		// TODO Auto-generated method stub
		String sql = "delete from t_administrator_role where admin_id = ? and role_id = ?";
		List<Object[]> objList = new ArrayList<>();
		for(Integer id : roleIdList){
			Object[] temp = new Object[2];
			temp[0] = adminId;
			temp[1] = id;
			objList.add(temp);
		}
		return this.executeBatchUpdate(sql, objList);
	}

	@Override
	public void deleteRolePermission(Integer roleId) {
		// TODO Auto-generated method stub
		String sql = "delete from t_role_permission where role_id = ?";
		this.executeUpdate(sql, roleId);
	}

	@Override
	public void deleteAdminRoleByAdmin(Integer adminId) {
		// TODO Auto-generated method stub
		String sql = "delete from t_administrator_role where admin_id = ?";
		this.executeUpdate(sql, adminId);
	}

	@Override
	public List<Role> adminRoleList(Integer adminId,Boolean flag) {
		// TODO Auto-generated method stub
//		String sql = "select * from t_role where role_id in ( "
//				+ "select role_id from t_administrator_role where admin_id = ? )";
		String sql = "select r.* from t_role r,t_administrator_role ar, t_administrator a "
				+ "where r.role_id = ar.role_id and ar.admin_id = a.admin_id "
				+ "and ar.role_id in (select role_id from t_administrator_role where admin_id = ?) "
				+ "and ar.admin_id = ? and r.enabled = 1 ";
		List<Role> roleList = this.executeQuery(sql, new Object[]{adminId,adminId});
		if(roleList != null && !roleList.isEmpty()){
			String tempStr = "select * from t_permission where permission_id "
					+ "in (select permission_id from t_role_permission where role_id = ?) and enabled = 1 and group_name = ? ";
			String permissionGroup = null;
			if(flag)
				permissionGroup = RoleServiceImpl.PLATFORM_PERMISSION_GROUP;
			else
				permissionGroup = RoleServiceImpl.ENTERPRISE_PERMISSION_GROUP;
			for(Role role : roleList){
				role.setPermissionList(permissionDao.executeQuery(tempStr, new Object[]{role.getRoleId(),permissionGroup}));
			}
		}
		return roleList;
	}

	@Override
	public List<Role> roleListResult(RoleDto dto) {
		// TODO Auto-generated method stub
		WhereClauseBuilder sbf = this.wrapWhereSQL(dto);
		return this.executeQuery(sbf.getSql(),sbf.getArgs());
	}

	@Override
	public List<Role> publicRoles(String name, String flag) {
		// TODO Auto-generated method stub
		String sql = " name = ? and enterprise_code = ? ";
		Object[] args = new Object[2];
		args[0] = name;
		args[1] = flag;
		List<Role> list = this.selectWhere(sql, args);
		return list;
	}

	@Override
	public List<Map<String, Object>> checkIsUsed(Integer roleId) {
		// TODO Auto-generated method stub
		String sql = "select * from t_administrator_role where role_id = ?";
		return this.queryForList(sql, roleId);
	}

	@Override
	public Boolean checkExistRole(Role role) {
		// TODO Auto-generated method stub
		List<Role> list = this.selectWhere(" name = ? and enterprise_code = ? ", 
				new Object[]{role.getName(),role.getEnterpriseCode()});
		if(list == null || list.isEmpty())
			return false;
		return true;
	}

}
